package com.mobisystems.youpark.settings;

import java.util.HashMap;
import java.util.Map;

import android.app.ActionBar;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.mobisystems.youpark.IPaymentForm;
import com.mobisystems.youpark.R;
import com.mobisystems.youpark.SettingsActivity;
import com.mobisystems.youpark.dialog.ErrorDialogFragment;
import com.parse.FunctionCallback;
import com.parse.ParseCloud;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.stripe.Stripe;
import com.stripe.android.model.Card;
import com.stripe.exception.APIConnectionException;
import com.stripe.exception.APIException;
import com.stripe.exception.AuthenticationException;
import com.stripe.exception.CardException;
import com.stripe.exception.InvalidRequestException;
import com.stripe.model.Customer;
import com.stripe.model.Token;


public class CreditCardActivity extends FragmentActivity implements IPaymentForm{
	private EditText etCreditCard;
	private BootstrapButton btnSaveCreditCard;
	private Spinner spinnerExpMonth;
	private Spinner spinnerExpYear;
	private EditText etCvc;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_credit_card);
		
		//using custom action bar
		ActionBar customActionBar = getActionBar();
		customActionBar.setDisplayShowHomeEnabled(false);
		customActionBar.setDisplayShowTitleEnabled(false);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.custom_actionbar, null);
        TextView titleTextView = (TextView) view.findViewById(R.id.title_text);
        titleTextView.setText("Credit Card Information");
        view.findViewById(R.id.button_settings).setVisibility(View.INVISIBLE);
        view.findViewById(R.id.button_switch_modes).setVisibility(View.GONE);
		ImageButton backButton = (ImageButton) view.findViewById(R.id.button_back);
		backButton.setVisibility(View.VISIBLE);
		backButton.setBackgroundResource(R.drawable.back_button);
		backButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				onBackPressed();
			}
		});
        customActionBar.setCustomView(view);
        customActionBar.setDisplayShowCustomEnabled(true);
		
		etCreditCard = (EditText) findViewById(R.id.etCreditCardNumber);
		btnSaveCreditCard = (BootstrapButton) findViewById(R.id.btnSaveCreditCard);
		spinnerExpMonth = (Spinner) findViewById(R.id.spinnerExpMonth);
		spinnerExpYear = (Spinner) findViewById(R.id.spinnerExpYear);
		etCvc = (EditText) findViewById(R.id.etCVC);
		
		btnSaveCreditCard.setOnClickListener(new OnClickListener() {
			

			@SuppressWarnings("unchecked")
			@Override
			public void onClick(View v) {
				Stripe.apiKey = "sk_test_waGgPKE1zA91Nru33emcGIUL";
				String number = getCardNumber();
				Integer exp_month = getExpMonth();
				Integer exp_year = getExpYear();
				String cvc = getCvc();
				
				Card card = new Card(number, exp_month, exp_year, cvc);
				
				boolean validation = card.validateCard();
				
				if(validation == true) {
					Map<String, Object> cardParams = new HashMap<String, Object>();
					Map<String, Object> tokenParams = new HashMap<String, Object>();
					
					cardParams.put("number", number);
					cardParams.put("exp_month", exp_month);
					cardParams.put("exp_year", exp_year);
					cardParams.put("cvc", cvc);
					tokenParams.put("card", cardParams);
					
					new ProcessCardInformation().execute(tokenParams);
					Intent settings = new Intent(CreditCardActivity.this, SettingsActivity.class);
					startActivity(settings);
					finish();
					
				} 
				else {
					handleError("You did not enter valid information");
					Intent settings = new Intent(CreditCardActivity.this, CreditCardActivity.class);
					startActivity(settings);
					finish();
				}														 
				
			}
		});
	}


	protected void handleError(String error) {
		DialogFragment fragment = ErrorDialogFragment.newInstance(R.string.validationErrors, error);
        fragment.show(getSupportFragmentManager(), "error");
		
	}

	@Override
	public String getCardNumber() {
		return etCreditCard.getText().toString();
	}

	@Override
	public String getCvc() {
		return etCvc.getText().toString();
	}

	@Override
	public Integer getExpMonth() {
		return getInteger(spinnerExpMonth);
	}

	@Override
	public Integer getExpYear() {
		return getInteger(spinnerExpYear);
	}
	
	private Integer getInteger(Spinner spinner) {
    	try {
    		return Integer.parseInt(spinner.getSelectedItem().toString());
    	} catch (NumberFormatException e) {
    		return 0;
    	}
    }
	
	
	
	public class ProcessCardInformation extends AsyncTask<Map<String, Object>, Void, String>{


		@Override
		protected String doInBackground(Map<String, Object>... params) {
			// TODO Auto-generated method stub
			Map<String, Object> cardParams = params[0];
			Map<String, Object> customerParams = new HashMap<String, Object>();
			ParseUser currentUser = ParseUser.getCurrentUser();
			String email = currentUser.getString("email");
			try {
				Token tokenResponse = Token.create(cardParams);
				String token = tokenResponse.getId();		
				System.out.println("Token--------------"+token);
				
				
				customerParams.put("description", email);
				customerParams.put("card", token); // obtained with Stripe.js

				Customer customerResponse = Customer.create(customerParams);
				String customerId = customerResponse.getId();
				currentUser.put("customerId", customerId);
				currentUser.put("creditCardToken", token);
				
				
				currentUser.saveInBackground();
				
				System.out.println("Token--------------"+customerId);
				
			} catch (AuthenticationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvalidRequestException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (APIConnectionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (CardException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (APIException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return null;
		}
		
	}
	
}
